import { defineStore } from 'pinia'
import { ref, reactive, unref, computed } from 'vue'
import { useStorage } from '@/hooks/web/useStorage'

const { get, set, clear } = useStorage()
interface UserInfo {
	[key : string] : any
}

export const useUserStore = defineStore('user', () => {
	const userInfo = reactive<Partial<UserInfo>>(get('userInfo', {}))
	const token = ref<string>(get('trioToken'))

	// 登录存储用户信息、token
	function onLogin(state : { userInfo : UserInfo, token : string }) : void {
		updateUserInfo(state.userInfo)
		token.value = state.token
		set('trioToken', unref(token))
	}

	// 退出登录
	function onLogOut() : void {
		clear()
		uni.reLaunch({
			url: '/pages/Login/login'
		})
	}

	// 是否登录
	const isLogin = () => !!token.value

	// 更新用户信息
	function updateUserInfo(info : UserInfo) {
		Object.assign(userInfo, info)
		set('userInfo', unref(userInfo))
	}

	// 获取token
	const getToken = () => token.value

	return {
		userInfo,
		getToken,
		onLogin,
		onLogOut,
		isLogin,
		updateUserInfo
	}
})